package workspace.teaweb.User.controllers;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import workspace.teaweb.User.pojo.dto.UserLoginParam;
import workspace.teaweb.User.pojo.dto.UserSaveParam;
import workspace.teaweb.User.pojo.vo.UserVO;
import workspace.teaweb.User.service.UserService;
import workspace.teaweb.base.response.JsonResult;
import workspace.teaweb.base.response.StatusCode;

import javax.servlet.http.HttpSession;


@Slf4j
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    UserService userService;

    //一、注册功能
    @PostMapping("save")
    public JsonResult save(@RequestBody UserSaveParam userSaveParam){
        log.debug("保存/注册用户:{}",userSaveParam);
        userService.saveUser(userSaveParam);//调用业务层中的saveUser方法
        return JsonResult.ok("注册用户成功!");
    }

    //二、登录功能
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("准备登录用户:{}",userLoginParam);
        UserVO userVO = userService.login(userLoginParam);

        session.setAttribute("user",userVO);//放入一个键值对，存储会话标识:{"user":userVO}

        log.debug("成功登录用户:{}",userVO);
        return JsonResult.ok(userVO);
    }


    //三、获取当前用户
    @GetMapping("currentUser")
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = userService.getCurrentUser(session);
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok("当前用户信息", userVO);
    }
    @GetMapping("currentUserId")
    public JsonResult getCurrentUserId(@ApiIgnore HttpSession session) {
        Long userId = userService.getCurrentUserId(session);
        if (userId == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok("当前用户ID", userId);
    }

    //四、用户信息修改功能
    @PostMapping("update")
    public JsonResult update(@RequestBody UserSaveParam userSaveParam,@ApiIgnore HttpSession session){
        log.debug("修改用户信息:{}",userSaveParam);

        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){ //未登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        userService.updateUser(userSaveParam);
        return JsonResult.ok("修改用户信息成功!");
    }


    //五、退出功能
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        //移除第二个方法中存了键值对，存储会话标识:{"user":userVO}
        session.removeAttribute("user");
    }



}
